<template>
  <view class="weighing-container">
    <!-- 头部信息 -->
    <view class="flex-1 overflow-y-auto">
      <view class="header-card">
        <view class="header-content">
          <wd-row>
            <wd-col :span="12" class="text-left">
              <text class="label">采购单号</text>
            </wd-col>
            <wd-col :span="12" class="text-right">
              <text class="value">{{ purchaseOrderInfo?.code }}</text>
            </wd-col>
          </wd-row>
          <wd-row>
            <wd-col :span="12" class="text-left">
              <text class="label">供应商</text>
            </wd-col>
            <wd-col :span="12" class="text-right">
              <text class="value">{{ purchaseOrderInfo?.companyName }}</text>
            </wd-col>
          </wd-row>
          <wd-row>
            <wd-col :span="12" class="text-left">
              <text class="label">产品名称</text>
            </wd-col>
            <wd-col :span="12" class="text-right">
              <text class="value">{{ purchaseOrder?.productName }}</text>
            </wd-col>
          </wd-row>
        </view>
      </view>

      <!-- 称重操作区 -->
      <view class="weight-card">
        <wd-picker :columns="scaleList" label="请选择台秤" v-model="selectedScale" />
        <view class="weight-control">
          <view class="weight-input-container">
            <input
              type="number"
              class="weight-input"
              v-model="currentWeight"
              placeholder="请输入重量"
              placeholder-class="placeholder-style"
            />
            <!-- <input
            type="number"
            class="weight-input"
            v-model="currentUnit"
            placeholder="请输入重量"
            placeholder-class="placeholder-style"
          /> -->
            <!-- <text class="weight-unit">kg</text> -->
          </view>
          <view class="button-group">
            <button class="btn-get" @tap="getWeight">获取重量</button>
            <button class="btn-confirm" @tap="confirmWeight">确认</button>
          </view>
        </view>
        <!-- <view class="weight-display">
        <view class="weight-text">
          <wd-input type="number" v-model="currentWeight" placeholder="请获取或输入重量" />
        </view>
        <view class="weight-actions">
          <wd-button type="primary" size="small" :round="false" @tap="getWeight">
            获取重量
          </wd-button>
          <wd-button type="success" size="small" :round="false" @tap="confirmWeight">
            确认
          </wd-button>
        </view>
      </view> -->
      </view>

      <view scroll-y style="max-height: 400rpx; overflow-y: auto">
        <view v-for="(record, index) in weightRecords" :key="record.code" class="weight-records">
          <wd-swipe-action>
            <view class="record-item">
              <view>
                <wd-text :text="record.createTime" class="record-time"></wd-text>
              </view>
              <view>
                <wd-text
                  :text="`${record.weight}${formatUnit(purchaseOrder?.unit)}`"
                  class="record-weight"
                ></wd-text>
              </view>
              <view>
                <wd-button
                  class="print-button"
                  size="small"
                  type="primary"
                  :round="false"
                  @click="printRecord(record.weight, index)"
                >
                  打印
                </wd-button>
              </view>
            </view>
            <template #right>
              <view class="delete-btn">
                <wd-icon
                  name="delete"
                  size="22px"
                  color="#ff4d4f"
                  @tap="deleteRecord(record, index)"
                ></wd-icon>
              </view>
            </template>
          </wd-swipe-action>
        </view>
      </view>

      <!-- 底部质检信息 -->
      <view class="inspection">
        <view class="stats">
          <view class="stat-item">
            <text class="stat-label">采购数量</text>
            <text class="stat-value">
              {{ purchaseOrder?.qty }}{{ formatUnit(purchaseOrder?.unit) }}
            </text>
          </view>
          <view class="stat-item">
            <text class="stat-label">实际数量</text>
            <text class="stat-value">{{ totalWeight }}{{ formatUnit(purchaseOrder?.unit) }}</text>
            <!-- <view class="editable-weight">
            <input
              type="digit"
              :value="totalWeight"
              disabled
              class="weight-input"
              style="border: none"
            />
            <text class="weight-unit">kg</text>
          </view> -->
          </view>
        </view>
        <view class="stats">
          <view class="stat-item">
            <text class="stat-label">合格数量</text>
            <view class="editable-weight">
              <input
                type="digit"
                v-model="qualifiedWeight"
                :max="totalWeight"
                class="weight-input"
              />
            </view>
          </view>
          <view class="stat-item">
            <wd-circle
              v-model="qualificationRate"
              :text="`合格率：${qualificationRate.toFixed(2)}%`"
              style="font-size: smaller"
            ></wd-circle>
          </view>
        </view>

        <!-- 照片上传 -->
        <view class="upload-section">
          <view class="upload-title">实物照片</view>
          <!-- 拍照上传 加载中 -->
          <wd-upload
            v-model:file-list="productPhotos"
            image-mode="aspectFill"
            :action="actionUrl"
            multiple
            :formData="physicalFormData"
          ></wd-upload>

          <view class="upload-title mt-2">检测照片（选填）</view>
          <wd-upload
            v-model:file-list="testPhotos"
            image-mode="aspectFill"
            multiple
            :action="actionUrl"
            :formData="reportFormData"
          ></wd-upload>
          <wd-button block :round="false" @tap="handleAddReport">新增化验单</wd-button>
        </view>
      </view>
    </view>
    <!-- 底部按钮 -->
    <view class="bottom-buttons">
      <wd-row>
        <wd-col :span="12">
          <wd-button type="info" block :round="false" @tap="printRecord(Number(totalWeight))">
            打印总重量
          </wd-button>
        </wd-col>
        <wd-col :span="12">
          <wd-button type="primary" block :round="false" @tap="handleSave">保存</wd-button>
        </wd-col>
      </wd-row>
    </view>
  </view>
</template>

<script lang="ts" setup>
import goodsReceiptApi, {
  PurchaseOrderDetailData,
  PurchaseOrderListData,
  ScaleCode,
  WeightRecord,
} from '@/api/goodsReceipt'
import { ref, computed } from 'vue'
import { useMessage, useToast } from 'wot-design-uni'
import FileApi from '@/api/file'
import { formatCurrentTime } from '@/utils/time'
import { formatUnit } from '@/utils/unit'

const fileUploadFormData = {
  physical: { bizType: 'physical' },
  report: { bizType: 'report' },
}
const physicalFormData = ref(fileUploadFormData.physical) as any
const reportFormData = ref(fileUploadFormData.report) as any

const message = useMessage()
const toast = useToast()

const actionUrl = computed(() => {
  return FileApi.uploadUrl
})

// 台秤列表
const scaleList = ref([
  { value: ScaleCode.SCALE_1, label: '1号台秤' },
  { value: ScaleCode.SCALE_2, label: '2号台秤' },
])
const selectedScale = ref<ScaleCode>()

// 重量数据
const weightData = ref<WeightRecord>({
  code: '',
  sourceCode: '',
  productName: '',
  productCode: '',
  weight: 0,
  createTime: '',
})
const currentWeight = ref<string>('0.00')
// const currentUnit = ref<string>('kg')

// 采购单号

const purchaseOrder = ref<PurchaseOrderDetailData>()
const purchaseOrderInfo = ref<PurchaseOrderListData>()

// 称重记录
const weightRecords = ref<WeightRecord[]>([])

// 照片
const productPhotos = ref([])
const testPhotos = ref([])
const totalWeight = computed(() => {
  return (
    weightRecords.value.reduce((sum, record) => sum + Number(record.weight), 0).toFixed(2) || '0.00'
  )
})

// const totalWeight = computed(() => {
//   weightRecords.value.reduce((sum, record) => sum + Number(record.weight), 0).toFixed(2) || 0.0
// })
const qualifiedWeight = ref(totalWeight.value)
// const qualifiedWeight = computed(() => {
//   // TODO: 根据业务规则计算合格重量
//   return totalWeight.value
// })

const qualificationRate = computed(() => {
  return Number((Number(qualifiedWeight.value) / Number(totalWeight.value)).toFixed(2)) * 100 || 0
})

// 获取重量
const getWeight = async () => {
  if (!selectedScale.value) {
    return toast.error('请先选择台秤')
  }
  try {
    // TODO: 调用获取重量API
    const res = await goodsReceiptApi.getScaleInfo(
      selectedScale.value,
      purchaseOrderInfo?.value.code,
      purchaseOrder.value.productCode,
    )
    console.log(res, '获取重量')
    weightData.value = res.data
    currentWeight.value = res.data.weight.toString()
    // weightData.value.createTime = res.data.createTime
    toast.success('获取重量成功')
  } catch (error) {
    console.log(error)
  }
}

// 确认重量
const confirmWeight = async () => {
  if (currentWeight.value === '0.00') {
    return toast.error('请先获取重量')
  }
  console.log(weightData.value)

  weightRecords.value.unshift({
    code: weightData.value.code,
    sourceCode: weightData.value.sourceCode,
    productName: weightData.value.productName,
    productCode: weightData.value.productCode,
    weight: Number(currentWeight.value),
    createTime: formatCurrentTime(),
  })
  currentWeight.value = '0.00'
  toast.success('添加称重记录成功')
}

// 打印记录
const printRecord = (weight: number, index?: number) => {
  // 如果称重记录为空 ，不允许打印
  if (weightRecords.value.length === 0) {
    toast.warning('请先称重')
    return
  }
  message
    .prompt({
      title: '是否确认打印标签？',
      inputValue: weight,
      inputPattern: /^[0-9]+(\.[0-9]{1,2})?$/,
      inputPlaceholder: '请输入重量',
      confirmButtonText: '确认打印',
      cancelButtonText: '取消',
    })
    .then((resp) => {
      console.log(resp)
      //将当前记录的重量改为修改的重量
      console.log(index)

      if (index !== undefined) weightRecords.value[index].weight = Number(resp.value)

      // 打印标签，标签样式 BASKET_CODE_TIMESTAMP
      // 获取时间戳
      const timestamp = new Date().getTime()

      const label = `s${timestamp};${purchaseOrder.value.productCode};${purchaseOrder.value.productName};${resp.value};${purchaseOrderInfo.value.code};${purchaseOrderInfo.value.companyName};`
      console.log(label, '打印标签')
      toast.success('打印成功')
    })
    .catch((error) => {
      console.log(error)
    })
}

// 删除记录
const deleteRecord = (record, index) => {
  message
    .confirm({
      title: '确认删除',
      msg: '是否确认删除该称重记录？',
    })
    .then(() => {
      weightRecords.value.splice(index, 1)
      toast.success('删除成功')
    })
}

// 保存
const handleSave = async () => {
  if (weightRecords.value.length === 0) {
    return toast.error('请至少添加一条称重记录')
  }
  console.log(productPhotos.value)

  if (productPhotos.value.length === 0) {
    return toast.error('请上传实物照片')
  }
  message
    .confirm({
      title: '确认保存',
      msg: '请检查是否打印过标签',
      confirmButtonText: '确认保存',
      cancelButtonText: '取消',
    })
    .then(async () => {
      const res = await goodsReceiptApi.savePurchaseReceive({
        // code: purchaseCode.value,
        productCode: purchaseOrder.value.productCode,
        qty: Number(purchaseOrder.value.qty),
        receiveQty: Number(totalWeight.value),
        qualifiedQty: Number(qualifiedWeight.value),
        orderCode: purchaseOrderInfo.value.code,
        parentCode: purchaseOrder.value.code,
        productName: purchaseOrder.value.productName,
        physicalImage: productPhotos.value.map((item) => JSON.parse(item.response).data),
        reportImage: testPhotos.value.map((item) => JSON.parse(item.response).data),
      })
      toast.success('保存成功')
      // code, status, companyName
      uni.navigateBack()
    })
}

// 新增化验单  TODO..
const handleAddReport = () => {
  uni.navigateTo({
    url: `/pages/GRreport/GRreport?purchaseOrder=${JSON.stringify(purchaseOrder.value)}&purchaseOrderInfo=${JSON.stringify(purchaseOrderInfo.value)}`,
  })
}

// 根据单号获取详情
const getPurchaseOrder = (code: string, productCode: string) => {
  goodsReceiptApi.getPurchaseOrderDetail(code).then((res) => {
    console.log(res, 'res')

    purchaseOrder.value = res.data.filter((item) => item.productCode === productCode)[0]
  })
}
// 根据单号获取采购单信息
const getPurchaseOrderInfo = (code) => {
  goodsReceiptApi
    .getPurchaseOrderList({ code, statusList: [1, 2, 3, 4, 5, 6], pageNum: 1, pageSize: 1 })
    .then((res: any) => {
      console.log(res, 'res')
      purchaseOrderInfo.value = res.data.list[0]
    })
}

// 页面加载
onLoad((options) => {
  console.log(options)

  getPurchaseOrder(options.purchaseCode, options.productCode)
  getPurchaseOrderInfo(options.purchaseCode)
})
</script>

<style lang="scss" scoped>
$primary-color: #3e7bfa;
$secondary-color: #36b8c2;
$success-color: #67c23a;
$warning-color: #e6a23c;
$danger-color: #f56c6c;
$background-color: #f5f7fa;
$card-background: #ffffff;
$text-primary: #303133;
$text-secondary: #606266;
$border-color: #ebeef5;
$box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
.weighing-container {
  display: flex;
  flex-direction: column;
  // height: calc(100vh - 100rpx);
  height: 100vh;
}
.header-card {
  padding: 20rpx;
  margin-bottom: 20rpx;
  font-size: 28rpx;
  background-color: #fff;
  box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.1);
  .value {
    font-size: 24rpx;
    color: $primary-color;
  }
}
.weight-card,
.record-card {
  padding: 20rpx;
  margin: 20rpx;
  margin-bottom: 20rpx;
  font-size: 28rpx;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.1);
  .value {
    font-size: 24rpx;
    color: $primary-color;
  }
}
.weight-control {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  margin-top: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  .weight-input-container {
    position: relative;
    flex: 1;
    margin-right: 60rpx;
    .weight-input {
      width: 80%;
      height: 80rpx;
      padding: 0 20rpx;

      font-size: 14px;
      color: #333;
      background-color: #f5f5f5;
      border-radius: 8rpx;
    }
    .weight-unit {
      position: absolute;
      top: 50%;
      right: 20rpx;
      font-size: 14px;
      color: #666;
      transform: translateY(-50%);
    }
  }
  .button-group {
    display: flex;
    gap: 20rpx;
    .btn-get {
      font-size: 14px;
      color: #fff;
      background-color: #4080ff;
    }
    .btn-confirm {
      font-size: 14px;
      color: #fff;
      background-color: #52c41a;
    }
  }
}
.inspection {
  flex-shrink: 0;
  padding: 30rpx;
  margin-top: 20rpx;
  background-color: #ffffff;
  .stats {
    display: flex;
    justify-content: space-between;
    margin-bottom: 30rpx;
    .stat-item {
      width: 100%;
      text-align: center;
      .stat-label {
        font-size: 14px;
        color: #666666;
      }
      .stat-value {
        display: block;
        margin-top: 10rpx;
        font-size: 16px;
        font-weight: bold;
        color: #333333;
      }
      .editable-weight {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 10rpx;
        .weight-input {
          height: 50rpx;
          padding: 0 10rpx;
          font-size: 16px;
          font-weight: bold;
          color: #333333;
          text-align: center;
          border: 1px solid #dddddd;
          border-radius: 6rpx;
        }
        .weight-unit {
          margin-left: 10rpx;
          font-size: 14px;
          color: #666666;
        }
      }
    }
  }
  .progress-bar {
    margin-bottom: 30rpx;
    .progress-text {
      margin-bottom: 10rpx;
      font-size: 14px;
      color: #666666;
    }
    .progress-track {
      height: 20rpx;
      overflow: hidden;
      background-color: #f5f5f5;
      border-radius: 10rpx;
      .progress-fill {
        height: 100%;
        background-color: #3e7bfa;
        transition: width 0.3s ease;
      }
    }
  }
}
.quality-card {
  padding: 20rpx;
  margin: 0 20rpx;
  margin-bottom: 200rpx;
  font-size: 28rpx;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.1);
  .value {
    font-size: 24rpx;
    color: $primary-color;
  }
}
.card-title {
  display: flex;
  align-items: center;
  justify-content: start;
  margin-bottom: 10rpx;
  font-weight: bold;
  color: #333;
  .card-text {
    font-size: 24rpx;
    color: #666;
  }
  .card-action {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.weight-display {
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 0 20rpx;
  .weight-text {
    display: flex;
    align-items: center;
    justify-content: center;
    .weight-value {
      font-size: 48rpx;
      font-weight: bold;
      color: $primary-color;
    }
  }
  .weight-actions {
    display: flex;
    justify-content: space-around;

    .wd-button {
      margin: 0 10rpx;
    }
  }
}
.weight-records {
  padding: 0 30rpx;
  .record-item {
    display: flex;
    align-items: center;
    justify-content: space-around;
    padding: 30rpx;
    margin-bottom: 20rpx;
    background-color: #ffffff;
    border-radius: 10rpx;
    .record-time {
      font-size: 14px;
      color: #666666;
    }
    .record-weight {
      font-size: 16px;
      font-weight: bold;
      color: #333333;
    }

    .print-button {
      display: flex;
      align-items: center;
      margin-left: 20rpx;
    }
  }
}
.upload-section {
  margin-top: 30rpx;

  .upload-title {
    margin-bottom: 20rpx;
    font-size: 28rpx;
    color: #666;
  }
}

.bottom-buttons {
  // position: fixed;
  // right: 0;
  // bottom: 0;
  // left: 0;
  height: 100rpx;
  padding: 20rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.delete-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100rpx;
  height: 100%;
}

.mt-2 {
  margin-top: 16rpx;
}
</style>
<style lang="scss"></style>
